// pages/login/index.js
const {
  Base
} = require('../../utils/base.js')
const {
  MemberModel
} = require('../../utils/member-model.js')
const {
  Config
} = require('../../utils/config.js')
const memberModel = new MemberModel()
const http = new Base()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dialogShow: false,
    encryptedDataUser: '',
    ivUser: '',
    encryptedDataPhone: '',
    ivPhone: '',
    code: '',
    formIds: '',
    shareData: {}
  },

  getUserInfo({
    detail
  }) {
    const {
      encryptedData,
      iv
    } = detail
    if (encryptedData) {
      this.setData({
        encryptedDataUser: encryptedData,
        ivUser: iv,
        dialogShow: true
      })
    }
  },

  getPhoneNumber({
    detail
  }) {
    this.setData({
      dialogShow: false
    })
    const {
      encryptedData,
      iv
    } = detail
    if (encryptedData) {
      this.setData({
        encryptedDataPhone: encryptedData,
        ivPhone: iv
      })
      this.register()
    }
  },

  refuse() {
    this.setData({
      dialogShow: false
    })
  },

  formSubmit(e) {
    this.getSubscribeMessage()
    // this.setData({
    //   formIds: e.detail.formId
    // })
  },

  register() {
    wx.checkSession({
      success: () => {
        http.request({
          url: '/wechat/applet/user/register',
          data: {
            sourcePartnerSign: app.globalData.sourcePartnerSign,
            code: this.data.code,
            encryptedDataUser: this.data.encryptedDataUser,
            ivUser: this.data.ivUser,
            encryptedDataPhone: this.data.encryptedDataPhone,
            ivPhone: this.data.ivPhone,
            appId: Config.appId,
            formId: this.data.formIds,
            uniGuid: app.globalData.uniGuid,
            shareFlag: !!app.globalData.isShare,
            shareMemberId: app.globalData.shareMemberId,
            shareActivityId: app.globalData.activityId,
            operatorId: this.data.shareData.operatorId,
            source: this.data.shareData.source,
            shareChannel: this.data.shareData.shareChannel,
            shopId: this.data.shareData.shopId
          },
          sCallback: ({
            data,
            error,
            status
          }) => {
            if (status === 200) {
              wx.setStorageSync('token', data.token)
              app.globalData.isLogin = true
              // this.assetTransfer()
              if (data.register) {
                this.registerGift()
              } else {
                wx.reLaunch({
                  url: '/pages/index/index'
                })
              }
            } else {
              this.getCode()
              wx.showToast({
                title: `${error}`,
                icon: 'none'
              })
            }
          },
          eCallback: () => {
            this.getCode()
            wx.showToast({
              icon: 'none',
              title: '会员注册失败'
            })
          }
        })
      },
      fail: () => {
        this.getCode()
        wx.showToast({
          icon: 'none',
          title: '时间太长，请重新登录'
        })
      }
    })
  },

  registerGift() {
    memberModel.registerGift({
      partnerSign: app.globalData.sourcePartnerSign,
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      data = data || []
      wx.reLaunch({
        url: `/pages/index/index?registerGifts=${JSON.stringify(data)}&encryptedData=true`
      })
    }).catch(() => {
      wx.reLaunch({
        url: '/pages/index/index'
      })
    })
  },

  /**
   * 1.点击【我知道了】显示订阅消息弹窗
   * 2.点击【积分商城】进入积分详情页面时
   * 3.会员授权成功后
   * 4.点击【会员中心】按钮
   */
  getSubscribeMessage: function () {
    memberModel.subscribeMessage({
      merchantId: wx.getStorageSync('merchantId'),
      position: 3
    }).then(data => {
      if (data && data.length > 0) {
        let tmplId = []
        data.forEach(element => {
          if (element.templateId) {
            tmplId.push(element.templateId)
          }
        })
        if (tmplId.length > 0) {
          wx.requestSubscribeMessage({
            tmplIds: tmplId,
            success(res) {},
            fail(err) {}
          })
        }
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shareData: JSON.parse(options.shareData || '{}')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getCode()
  },

  getCode() {
    wx.login({
      success: ({
        code
      }) => {
        this.setData({
          code
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})